var CryptoJS = require('des.js');
const formatTime = (val, num) => {
    const date = new Date(val);
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()
    if (num === 0) {
        return [year, month, day].map(formatNumber).join('-')
    } else if(num === 1) {
        return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
    } else if (num === 2) {
        return year + '年' + month + '月';
    }
}

const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}


const onMoney = (val) => {
    //金额转换 分->元 保留2位小数 并每隔3位用逗号分开 1,234.56
    var str = (val * 100 / 100).toFixed(2) + '';
    var intSum = str.substring(0, str.indexOf(".")).replace(/\B(?=(?:\d{3})+$)/g, ',');//取到整数部分
    var dot = str.substring(str.length, str.indexOf("."))//取到小数部分搜索
    var ret = intSum + dot;
    return ret;
}
/**
 * 单提示函数
 */
const showToast = (tit) => {
    if (!tit) return;
    wx.showToast({
        title: tit,
        icon: 'none',
        duration: 1500
    });
}

/**
 * 基础用户信息的获取
 */
function baseLogin(fn) {
    wx.login({
        success(res) {
            var code = res.code;
            wx.getUserInfo({
                success(res) {
                    var encryptedData = res.encryptedData;
                    var iv = res.iv;
                    fn(encryptedData, code, iv)//这里获取到的数据可以去和后台换用户的资料 unionid/用户基本信息之类的
                },
                fail(res) {
                    wx.reLaunch({
                        url: '/pages/index/index'
                    })
                },
            })
        }
    })
}

/**
 * 图片上传的封装处理
 */

function upImgAllSuccssAll(res, formData, success, url) {
    var upImgBoxArr = res.tempFilePaths;
    var imgarr = [];
    for (var j in upImgBoxArr) {
        if (res.tempFiles[j].size > 2097152) {
            http.showModal('有图片已超过2MB,您可以选择压缩图片以后重新上传', false, () => { })
            continue;
        }
        var turnsImgUrl = wx.uploadFile({
            url: http + url,
            filePath: upImgBoxArr[j],
            name: 'fileData',
            herder: { 'content-type': 'multipart/form-data;' },
            formData: formData,
            success: (resp) => {
                success(resp)
            },
        });
    }
}
/**
 * 手机号校验
 */
function telCheck(val, text){
    var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1})|(19[0-9]{1}))+\d{8})$/;
    if (val.length === 0) {
        showToast('输入的'+ text +'手机号为空');
        return false;
    } else if (val.length < 11) {
        showToast(text + '手机号长度有误！');
        return false;
    } else if (!myreg.test(val)) {
        showToast(text + '手机号有误！');
        return false;
    }
    return true;
}
/**
 * 手机号校验
 */
function passWord(val) {
    if (val.length === 0) {
        showToast('输入的密码为空');
        return false;
    } else if (val.length < 6) {
        showToast('密码长度有误！');
        return false;
    }
    return true;
}
/**
 * 身份证号校验
 */
function isCardNo(val) {
    // 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X  
    var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    if (reg.test(val) === false) {
        showToast('身份证输入不合法');
        return false;
    }
    return true;
}
/**
 * 银行卡号校验
 */
function CheckBankNo(val) {
    if (val.length === 0) {
        showToast('请填写银行卡号');
        return false;
    }
    return true;
}

function nonEmpty(val, text) {
    if (val.length === 0) {
        showToast(text);
        return false;
    }
    return true;
}

function nonCompare(val, text) {
    if (val) {
        showToast(text);
        return false;
    }
    return true;
}

function Encrypt(pwd, random) {
    var encrypted = CryptoJS.DES.encrypt(pwd, CryptoJS.enc.Utf8.parse(random), {
        iv: CryptoJS.enc.Utf8.parse('XINGFUJI'),
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    return encrypted.toString();
}
function Decrypt(pwd, random) {
    var decrypt = CryptoJS.DES.decrypt(pwd, CryptoJSenc.Utf8.parse(random), { 
        iv: CryptoJS.enc.Utf8.parse('XINGFUJI'), 
        mode: CryptoJS.mode.CBC, 
        padding: CryptoJS.pad.Pkcs7
    });
    console.log(CryptoJS.enc.Utf8.stringify(decrypt))
    return CryptoJS.enc.Utf8.stringify(decrypt).toString();
} 

function Encrypts(word) {
    var key = CryptoJS.enc.Utf8.parse('DontTellOtherpeopleplzas1238fdja0hghn');
    var iv = CryptoJS.enc.Utf8.parse('nopainno');
    var srcs = CryptoJS.enc.Utf8.parse(word);
    var encrypted = CryptoJS.DES.encrypt(srcs, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    return encrypted.toString();
}



module.exports = {
    formatTime: formatTime,
    onMoney: onMoney,
    showToast: showToast,
    baseLogin: baseLogin,
    passWord: passWord,
    upImgAllSuccssAll: upImgAllSuccssAll,
    telCheck: telCheck,
    isCardNo: isCardNo,
    CheckBankNo: CheckBankNo,
    nonEmpty: nonEmpty,
    nonCompare: nonCompare,
    Encrypt: Encrypt,
    Decrypt: Decrypt,
    Encrypts: Encrypts
}